from models_final import get_asr, get_my_qwq
from prompts_final import safety_prompt
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
import gradio as gr

# 初始化模型
asr_model = get_asr()
safety_model = get_my_qwq()

# 全局变量用于存储转录结果
transcription_result = None


def get_safe_transcription(audio_file):
    global transcription_result
    try:
        # 读取音频文件
        with open(audio_file.name, "rb") as f:
            transcription_result = asr_model.transcriptions(f.read())["text"]
        return transcription_result
    except Exception as e:
        return f"处理出错: {str(e)}"


def get_safe_summary():
    global transcription_result
    if transcription_result is None:
        return "当前语音识别未结束，请先进行语音识别"
    try:
        chain = safety_prompt | safety_model | StrOutputParser()
        summary = chain.invoke({"comment": transcription_result})
        return summary
    except Exception as e:
        return f"处理出错: {str(e)}"


# 创建Gradio界面
# with gr.Blocks(theme=gr.themes.Soft()) as interface:  # 使用Soft主题
#     # 标题与描述
#     gr.Markdown(
#         """
#         # 🚧 施工作业过程安全隐患智能排查助手
#         ### 上传作业录音文件（MP3/WAV），自动排查安全隐患
#         """
#     )

#     # 文件上传与结果显示区域
#     with gr.Row():
#         with gr.Column(scale=1):
#             audio_input = gr.File(label="上传作业录音", file_types=[".mp3", ".wav"])
#             gr.Markdown("支持的格式：MP3、WAV")
#         with gr.Column(scale=2):
#             transcription_output = gr.Textbox(
#                 label="语音识别结果", lines=5, interactive=False
#             )
#             summary_output = gr.Textbox(
#                 label="隐患排查结果", lines=10, interactive=False
#             )

#     # 操作按钮区域
#     with gr.Row():
#         transcribe_button = gr.Button("开始语音识别", variant="primary")
#         summary_button = gr.Button("开始隐患排查", variant="secondary")

#     # 状态提示区域
#     status_message = gr.Markdown("等待操作...")

    # 按钮点击事件绑定
#     def on_transcribe_click(audio_file):
#         if not audio_file:
#             return "", "请上传有效的音频文件！"
#         result = get_transcription(audio_file)
#         status = "语音识别完成" if "处理出错" not in result else "语音识别失败"
#         return result, status

#     def on_summary_click():
#         result = get_summary()
#         status = "隐患排查完成" if "处理出错" not in result else "隐患排查失败"
#         return result, status

#     transcribe_button.click(
#         fn=on_transcribe_click,
#         inputs=audio_input,
#         outputs=[transcription_output, status_message],
#     )
#     summary_button.click(
#         fn=on_summary_click,
#         inputs=None,
#         outputs=[summary_output, status_message],
#     )

# if __name__ == "__main__":
#     interface.launch(server_port=8080)